import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import {
    Grid,
    Typography,
    colors,
    Button,
    OutlinedInput,
    InputAdornment,
    Tabs,
    Tab,
    Box,
} from '@material-ui/core';
import Pagination from '@material-ui/lab/Pagination';
import { Image, Icon } from 'components/atoms';
import { callGetNewsApi , callPostNewsApi} from 'utils/networking';

import { useDispatch, useSelector } from 'react-redux'
import { Hero } from "../../components"
import { useLocation } from 'react-router-dom/cjs/react-router-dom.min';

const useStyles = makeStyles(theme => ({
    root: {
        width: "100%",
        padding: "0 20px",
        background: '#000',
        marginTop: "-10px",
        "& .MuiTabs-indicator": {
            display: "none"
        },
        "& .MuiTab-root": {
            color: "white",
            paddingLeft: "25px",
            paddingRight: "25px",
        },
        "& .MuiTab-wrapper": {
            padding: "0 8px",
            borderRadius: "2px",
        },
        "& .Mui-selected .MuiTab-wrapper": {
            background: "#E24575",
        },
    },
    title: {
        textAlign: "center",
        fontFamily: "HurmeGeometricSans3-Black",
        fontSize: "56px",
        fontStyle: "normal",
        fontWeight: 700,
        lineHeight: "normal",
        color: "rgba(30, 30, 30, 1)",
        padding: "50px 0",
        [theme.breakpoints.up('md')]: {
            fontSize: "63px",
        },
    },
    typography: {
        fontFamily: "HurmeGeometricSans3-Black",
        fontSize: "40px",
        fontStyle: "normal",
        fontWeight: 700,
        lineHeight: "40px",
        textTransform: "uppercase",
        color: "#7E53F9",
        [theme.breakpoints.up('md')]: {
            fontSize: "80px",
            lineHeight: "85px",
        },
        textAlign: "center",
    },
    typography1: {
        color: "#fff",
    },
    typography2: {
        color: "#000",
        lineHeight: "normal",
        fontSize: "25px",
    },
    typography3: {
        fontSize: "16px",
        lineHeight: "normal",
        color: "#C6C6CA",
    },
    typography4: {
        fontSize: "16px",
        lineHeight: "normal",
        color: "#C6C6CA",
    },
    grid: {
        padding: "10px",
    },
    gridItem: {
        padding: "10px",
    },
    searchTitle: {
        fontSize: "32px",
        lineHeight: "1.2",
        margin: "15px 0 30px 10px",
    },
    filter: {
        fontSize: "20px",
        color: "#E24575",
        margin: "10px 0 0 10px",
    },
    filterItem: {
        fontSize: "18px",
        color: "#B4B4B4",
        margin: "16px",
        cursor: "pointer",
        marginRight: "0",
        lineHeight: "32px",
    },
    select: {
        fontSize: "20px",
        color: "#E24575",
        margin: "20px 0 20px 35px",
    },
    selectItem: {
        fontSize: "16px",
        cursor: "pointer",
        lineHeight: "40px",
    },
    image: {
        position: "relative",
        height: "250px",
        borderRadius: "8px",
        overflow: "hidden",
        [theme.breakpoints.up('md')]: {
            height: "250px",
        },
        [theme.breakpoints.up('md')]: {
            height: "200px",
        },
        [theme.breakpoints.up('lg')]: {
            height: "300px",
        },
    },
    img: {
        objectFit: "cover"
    },
    adImage: {
        borderRadius: "8px",
        overflow: "hidden",
        marginTop: "30px",
        display: "none",
        "& span": {
            verticalAlign: "middle",
        },
        [theme.breakpoints.up('md')]: {
            display: "block",
        },
    },
    adLeft: {
        marginRight: "50px"
    },
    adRight: {
        marginLeft: "50px"
    },
    medias: {
        minHeight: "50vh",
        [theme.breakpoints.up('md')]: {
            minHeight: "100vh",
        },
    },
    pagination: {
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        padding: "20px 0",
        "& .MuiPaginationItem-page": {
            backgroundColor: "#232637",
            color: "#FFFFFF",
        },
        "& .Mui-selected": {
            backgroundColor: "#E24575",
        },
        "& .MuiPaginationItem-ellipsis": {
            color: "#FFFFFF",
        },
    },
    muiButton: {
        color: '#FFFFFF',
        width: '70%',
        marginTop:"10px",
    },
    textNum: {
        position: "absolute",
        right: "10px",
        bottom: "10px",
        color: "#9EFF00",
        fontSize: "20px",
        [theme.breakpoints.up('md')]: {
            fontSize: "32px",
        },
        [theme.breakpoints.up('lg')]: {
            fontSize: "38px",
        },
    }
}));


const filterText = ["Picanha turducken", "Prosciutto frankfurter", "Ribeye sausage",]

function Result() {

    const classes = useStyles();

    const [searchKey, setSearchKey] = useState('');

    const [voteInfoData, setVoteInfoData] = useState({
        data: [],
    });

    const [voteData, setVoteData] = useState([]);
    
    const [offset, setOffset] = useState(1);
    const [count, setCount] = useState(0);

    const dispatch = useDispatch()
    const location = useLocation();

    const state = location.state

    const searchBlogs = () => {
        getServerSideProps()
    }

    const [filterIndex, setFilterIndex] = useState([]);

    const handleFilter = (index) => {
        console.log(filterIndex)
        if (filterIndex.some(item => item == index)) {
            setFilterIndex(filterIndex.filter(item => item != index))
        } else {
            setFilterIndex([...filterIndex, index])
        }
    }

    useEffect(() => {
        getServerSideProps()
        getServerProps()
    }, [])

    const handleSelect = () => {
        setFilterIndex([0, 1, 2])
    }

    const handleDeselect = () => {
        setFilterIndex([])
    }

    useEffect(() => {
        // getServerSideProps()
    }, [searchKey, offset])

    const getServerSideProps = async () => {
        callGetNewsApi(`vote/sub_categories_info?sub_categories_id=${state?.sub_id}&search_key=${searchKey}`, dispatch, (data) => {
            setVoteInfoData(data);
            setCount(data.counts.total_pages);
        })
    }

    const getServerProps = async () => {
        callGetNewsApi(`vote/sub_categories?category_id=${state.id}`, dispatch, (data) => {
            setVoteData(data.filter(item => item.vote_sub_categories_id === state.id)[0]);
        })
    }

    const handlePagination = (_, value) => {
        setOffset(value)
    }
        
    const handleNum = (num, total) => {
        if (Number(total) && Number(num)) {
            return Math.round(Number(num) / Number(total) * 100)
        } else {
            return 0
        }
    }

    const voted = (artist_id) => {
        const param = {
            artist_id: artist_id
        }
        callPostNewsApi('vote/update_vote', param, dispatch, (data) => {
            getServerProps()
            getServerSideProps()
        })
    }

    return (
        <div className={classes.root} data-aos="fade-up">
            <Hero setSearchKey={setSearchKey} searchBlogs={searchBlogs} location={voteData} />
            <Grid container>
                <Grid item xs={12} sm={12} md={3}>
                    <div className={classes.itemContent}>
                        <p className={classes.filter}>Filter</p>
                        <div className={classes.select}>
                            <p className={classes.selectItem} onClick={handleSelect}>Select All</p>
                            <p className={classes.selectItem} onClick={handleDeselect}>Deselect All</p>
                        </div>

                        <div>
                            {
                                filterText.map((item, index) => (<p key={index}>
                                    <Icon
                                        fontIconClass="fas fa-check"
                                        style={{ opacity: filterIndex.some(item => item == index) ? 1 : 0, color: "#E24575" }}
                                    />
                                    <span className={classes.filterItem} onClick={() => handleFilter(index)}>{item}</span></p>
                                ))
                            }
                        </div>
                        <div className={classes.adLeft}>
                            <div className={classes.adImage}>
                                <Image
                                    src={state?.ad[0]?.image_url}
                                    alt={state?.ad[0]?.image_url}
                                    srcSet={state?.ad[0]?.image_url}
                                    lazyProps={{ width: '100%', height: '100%' }}
                                />
                            </div>
                        </div>
                    </div>
                </Grid>
                <Grid item xs={12} md={9}>
                    <Box sx={{ width: '100%' }}>
                        <div className={classes.medias} data-aos="fade-up">
                            <Grid container>
                                {
                                    voteInfoData?.data.map((item, index) => (<Grid item xs={6} md={4} container className={classes.grid} key={index}>
                                        <Grid item xs={12} >
                                            <div className={classes.image}>
                                                <Image
                                                    src={item?.avatarURL}
                                                    alt={item?.avatarURL}
                                                    srcSet={item?.avatarURL}
                                                    lazyProps={{ width: '100%', height: '100%' }}
                                                    className={classes.img}
                                                />
                                                <div className={classes.textNum}>
                                                    {handleNum(item?.vote_num, voteData?.vote_num)}%
                                                </div>
                                            </div>
                                        </Grid>
                                        <Grid item xs={12} className={classes.gridItem} container alignItems='center' direction="column">
                                            <Typography className={clsx(classes.typography, classes.typography3)}>{item.name}</Typography>
                                            <Button className={classes.muiButton} onClick={() => voted(item.id)} color={item.is_vote ? "inherit" : "primary"} style={{ background: item.is_vote ? "#7E53F9" : "#787C85" }}>
                                                {
                                                    item.is_vote ? "Vote" : "Cancel Vote"
                                                }
                                            </Button>
                                        </Grid>
                                    </Grid>))
                                }
                            </Grid>
                        </div>
                        <div className={classes.pagination}>
                            <Pagination count={count} variant="outlined" shape="rounded" onChange={handlePagination} />
                        </div>
                    </Box>
                </Grid>
            </Grid>
        </div>
    )
}

Result.propTypes = {
    /**
     * External classes
     */
    className: PropTypes.string,
};

export default Result

